const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const bcconst = require('common/bcconst');
const metaFactory = require('../metadata/factory');
const serviceFactory = require('../services/factory');
const { config, webhook } = require('@imtbl/sdk');

async function procEvent(event, rsp) {
  console.log(event);
  const idx = 0;
  const dbKey = 'BcEventDb' + idx;
  const {err, conn} = await app.getDbConn(dbKey);
  if (err) {
    rsp.status(500).send(err);
    console.log(err);
    return;
  }
  try {
    const eventName = event.event_name;
    const eventId = event.event_id;
    const chain = event.chain;
    await conn.upsert(
      't_webhook_event',
      [
        ['event_id', eventId],
      ],
      [],
      [
        ['event_name', eventName],
        ['event_id', eventId],
        ['chain', chain],
        ['raw_data', utils.jsonEncode(event)],
      ]
    );
    rsp.send(utils.jsonEncode({"status": "ok"}));
  } catch (e) {
    console.log(e);
    rsp.status(500).send(e);
  } finally {
    conn.release();
  }
}

async function webhooks(req, rsp) {
  console.log(req.body);

  const events = [];
  let sdkEnv = config.Environment.PRODUCTION;
  if (!utils.isOnlineEnv()) {
    console.log('SANDBOX Environment');
    sdkEnv = config.Environment.SANDBOX;
  }
  await webhook.handle( // this method will handle the subscription confirmation and signature & sender verification
    req.body,
    sdkEnv, // or config.Environment.PRODUCTION
    {
      all: (event) => { // all events will trigger this handler, even if they have a specific handler already.
        events.push(event);
      }
    }
  );

  if (events.length > 0) {
    await procEvent(events[0], rsp);
  } else {
    rsp.status(500).send("no event");
  }
}

function init() {
  app.post('/api/webhooks', webhooks);
}

exports.init = init;
